package class1;

import java.util.Arrays;

/**
 * 冒泡排序
 */
public class Code04_bubbleSort {

    public static void main(String[] args) {

        int[] arr = new int[]{2, 5, 1, 9, 12, 6, 7, 3, 1};
        bubbleSort(arr);
        System.out.println(Arrays.toString(arr));

        int[] arr1 = new int[]{2, 5, 1, 9, 12, 6, 7, 3, 1};
        bubbleSort2(arr1);
        System.out.println(Arrays.toString(arr1));
    }

    public static void bubbleSort(int[] arr) {

        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    swap(arr, j, i);
                }
            }
        }
    }

    public static void bubbleSort2(int[] arr) {
        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j+1);
                }
            }
        }
    }

    public static void swap(int[] arr, int x, int y) {
        int t = arr[x];
        arr[x] = arr[y];
        arr[y] = t;
    }
}
